package com.banksoft.admin.service.impl;

import com.banksoft.admin.SystemCache;
import com.banksoft.admin.bean.AmountType;
import com.banksoft.admin.dao.*;
import com.banksoft.admin.entity.*;
import com.banksoft.admin.service.UserMoneyService;
import com.banksoft.util.StringNumber;
import com.banksoft.util.StringUtil;
import com.banksoft.util.UUIDFactory;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by vanjoger on 2017/1/5.
 */
@Service
@Transactional
public class UserMoneyServiceImpl implements UserMoneyService {

    @Autowired
    UserMoneyDao userMoneyDao;
    @Autowired
    BaseMyBatisDao baseMyBatisDao;

    @Override
    public UserMoney findByUserId(String userId) {
        List<UserMoney> moneys = userMoneyDao.findByUserId(userId);
        UserMoney money = null;
        if(StringUtil.isNotEmpty(moneys))
            money = moneys.get(0);
        return money;
    }

    @Override
    public JSONObject updateAmount(String id, String type, String amount, HttpServletRequest request) {
        UserMoney money = this.baseMyBatisDao.findById(UserMoneyDao.class,id);
        if(money==null)
            return StringUtil.FmtResult(false,"没有找到数据",null);
        if(!StringUtil.isNotNull(type))
            return StringUtil.FmtResult(false,"请选择操作方式",null);
        if(!StringUtil.isNotNull(amount))
            return StringUtil.FmtResult(false,"请输入调整的金额",null);

        float d = Float.parseFloat(amount);
        String amountType = "";
        String beforeCash = money.getCash();
        String beforeBonus = money.getBonus();
        String beforeFrozenAmount = money.getFrozenAmount();
        if(type.equals("1")){
            if(Float.parseFloat(StringNumber.sub(money.getCash(),d+""))<0)
                return StringUtil.FmtResult(false,"现金余额不足",null);
            money.setCash(StringNumber.sub(money.getCash(),d+""));
            money.setFrozenAmount(StringNumber.add(money.getFrozenAmount(),d+""));
            amountType = AmountType.FrozenCash.name();
        }else if(type.equals("3")){
             if(Float.parseFloat(StringNumber.sub(money.getBonus(),d+""))<0)
                return StringUtil.FmtResult(false,"购物余额不足",null);
            money.setBonus(StringNumber.sub(money.getBonus(),d+""));
            money.setFrozenAmount(StringNumber.add(money.getFrozenAmount(),d+""));
            amountType = AmountType.FrozenBonus.name();
        }else if(type.equals("2")){
            if(Float.parseFloat(StringNumber.sub(money.getFrozenAmount(),d+""))<0)
                return StringUtil.FmtResult(false,"冻结余额不足，无法解冻现金",null);
            money.setCash(StringNumber.add(money.getCash(),d+""));
            money.setFrozenAmount(StringNumber.sub(money.getFrozenAmount(),d+""));
            amountType = AmountType.AddCash.name();
        }else if(type.equals("4")){
            money.setBonus(StringNumber.add(money.getBonus(),d+""));
            if(Float.parseFloat(StringNumber.sub(money.getFrozenAmount(),d+""))<0)
                return StringUtil.FmtResult(false,"冻结余额不足，无法解冻现金",null);
            money.setBonus(StringNumber.add(money.getBonus(),d+""));
            money.setFrozenAmount(StringNumber.sub(money.getFrozenAmount(),d+""));
            amountType = AmountType.AddBonus.name();
        }
        this.baseMyBatisDao.update(UserMoneyDao.class,money);

        AmountLog log = new AmountLog();
        log.setId(UUIDFactory.random());
        log.setUserId(money.getUserId());
        log.setUserName(money.getUserName());
        log.setBeforeCash(beforeCash);
        log.setBeforeBonus(beforeBonus);
        log.setType(amountType);
        String content = "";
        if(type.equals("1")){
            log.setCash("-"+amount);
            log.setBonus("0");
            content = "冻结现金余额";
        }else if(type.equals("2")){
            log.setCash(amount);
            log.setBonus("0");
            content = "解冻现金余额";
        }else if(type.equals("3")){
            log.setCash("0");
            log.setBonus("-"+amount);
            content = "冻结购物余额";
        }else if(type.equals("4")){
            log.setCash("0");
            log.setBonus(amount);
            content = "解冻购物余额";
        }
        log.setAfterCash(money.getCash());
        log.setAfterBonus(money.getBonus());
        log.setBeforeFrozenAmount(beforeFrozenAmount);
        log.setAfterFrozenAmount(money.getFrozenAmount());
        log.setCreateTime(new Date().getTime());
        this.baseMyBatisDao.insert(AmountLogDao.class,log);

        saveLog(request,content);
        return StringUtil.FmtResult(true,"操作成功",money);
    }

    @Override
    public JSONObject changeAmount(String id, String cash, String bonus, String frozenAmount, HttpServletRequest request, String userId, String remark) {
        UserMoney money = this.baseMyBatisDao.findById(UserMoneyDao.class,id);
        User user = this.baseMyBatisDao.findById(UserDao.class,userId);
        String beforeCash = "0";
        String beforeBonus = "0";
        String beforeFrozenAmount = "0";
        if(money==null) {
            money = new UserMoney();
            money.setId(UUIDFactory.random());
            money.setUserId(user.getId());
            money.setUserName(user.getNickName());
            money.setCash(cash);
            money.setBonus(bonus);
            money.setFrozenAmount(frozenAmount);
            money.setTotalAmount(StringNumber.add(StringNumber.add(cash,bonus),frozenAmount));
            this.baseMyBatisDao.insert(UserMoneyDao.class,money);
        }else{
            beforeCash = money.getCash();
            beforeBonus = money.getBonus();
            beforeFrozenAmount = money.getFrozenAmount();
            money.setCash(cash);
            money.setBonus(bonus);
            money.setFrozenAmount(frozenAmount);
            money.setTotalAmount(StringNumber.add(StringNumber.add(cash,bonus),frozenAmount));
            this.baseMyBatisDao.update(UserMoneyDao.class,money);
        }

        AmountLog log = new AmountLog();
        log.setId(UUIDFactory.random());
        log.setUserId(money.getUserId());
        log.setUserName(money.getUserName());
        log.setBeforeCash(beforeCash);
        log.setBeforeBonus(beforeBonus);
        log.setType(AmountType.HandleFee.name());
        log.setAfterCash(money.getCash());
        log.setAfterBonus(money.getBonus());
        log.setBeforeFrozenAmount(beforeFrozenAmount);
        log.setAfterFrozenAmount(money.getFrozenAmount());
        log.setCreateTime(new Date().getTime());
        log.setDataName(remark);
        this.baseMyBatisDao.insert(AmountLogDao.class,log);

        saveLog(request,"调整用户资金余额");
        return StringUtil.FmtResult(true,"操作成功",money);
    }

    @Override
    public List<UserMoney> listAll(Map<String, Object> map) {
        return this.userMoneyDao.listAll(map);
    }

    /**
     * 保存系统日志
     * @param request
     * @param content
     */
    private void saveLog(HttpServletRequest request,String content){
        Admin admin = (Admin) request.getSession().getAttribute(SystemCache.SESSION_ADMIN);
        SystemLog systemLog = new SystemLog();
        systemLog.setId(UUIDFactory.random());
        systemLog.setOperateName(admin.getLoginName());
        systemLog.setOperateContent(content);
        systemLog.setIp(request.getRemoteHost());
        systemLog.setLogDate(new Date().getTime());
        this.baseMyBatisDao.insert(LogDao.class,systemLog);
    }

}
